//
//  FGHelpTemplateView.m
//  lite
//
//  Created by feige on 2022/11/2.
//

#import "FGHelpTemplateView.h"
#import "UIColor+FGChat.h"
#import "UIView+FGLayout.h"

@interface FGHelpTemplateCategoryViewCell()

@end

@implementation FGHelpTemplateCategoryViewCell

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        // titleLabel
        _titleLabel = [UILabel new];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
        [self.contentView addSubview:_titleLabel];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    _titleLabel.frame = self.contentView.bounds;
}

@end

@interface FGHelpTemplateCategoryView()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) NSArray<NSString *> *dataArray;
@property (nonatomic, assign) NSInteger selectedIndex;
@end

@implementation FGHelpTemplateCategoryView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        // collectionView
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 28;
        layout.minimumInteritemSpacing = 28;
        layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        [_collectionView registerClass:FGHelpTemplateCategoryViewCell.class forCellWithReuseIdentifier:@"FGHelpTemplateCategoryViewCell"];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [self addSubview:_collectionView];
        
        // lineView
        _lineView = [UIView new];
        _lineView.backgroundColor = [UIColor fg_colorWithString:@"#558DFF"];
        _lineView.layer.cornerRadius = 1;
        [_collectionView addSubview:_lineView];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    _collectionView.frame = self.bounds;
    _lineView.hidden = !_dataArray || _dataArray.count == 0;
    [self setupLineViewFrame:NO];
}

#pragma mark - Private Method

// 获取字符串宽度
- (float)widthForString:(NSString *)value
                   font:(UIFont *)font
                 height:(float)height
{
    UIFont *textFont = font ? font : [UIFont systemFontOfSize:[UIFont systemFontSize]];
    CGSize textSize;
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    NSDictionary *attributes = @{NSFontAttributeName: textFont,
                                 NSParagraphStyleAttributeName: paragraph};
    textSize = [value boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height)
                                   options:(NSStringDrawingUsesLineFragmentOrigin |
                                            NSStringDrawingTruncatesLastVisibleLine)
                                attributes:attributes
                                   context:nil].size;
    return ceil(textSize.width);
}

- (void)setupLineViewFrame:(BOOL)animation
{
    UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:self.selectedIndex inSection:0]];
    if (!cell) {
        return;
    }
    CGRect cellFrame = cell.frame;
    
    [UIView animateWithDuration:animation ? 0.25f : 0 animations:^{
        self.lineView.frame = CGRectMake(cellFrame.origin.x + (cellFrame.size.width - 45) / 2.0f, 35, 45, 2);
    }];
}

#pragma mark - Public Method

- (void)fillData:(NSArray *)titles {
    _dataArray = titles;
    [self.collectionView reloadData];
    
    if (_dataArray && _dataArray.count > 0) {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
        CGFloat width = [self widthForString:_dataArray.firstObject font:[UIFont systemFontOfSize:14 weight:UIFontWeightMedium] height:20];
        self.lineView.frame = CGRectMake(10 + (width - 45) / 2.0f, 35, 45, 2);
    }
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = self.dataArray[indexPath.row];
    
    FGHelpTemplateCategoryViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FGHelpTemplateCategoryViewCell" forIndexPath:indexPath];
    cell.titleLabel.text = title;
    cell.titleLabel.textColor = self.selectedIndex == indexPath.row ? [UIColor fg_colorWithString:@"#558DFF"] : [UIColor blackColor];
    return cell;
    
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedIndex = indexPath.row;
    [self setupLineViewFrame:YES];
    
    [self.collectionView reloadData];
    
    if ([self.delegate respondsToSelector:@selector(helpTemplateCategoryViewDidSelectedIndex:)]) {
        [self.delegate helpTemplateCategoryViewDidSelectedIndex:self.selectedIndex];
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = self.dataArray[indexPath.row];
    CGFloat width = [self widthForString:title font:[UIFont systemFontOfSize:14 weight:UIFontWeightMedium] height:20];
    
    return CGSizeMake(width, self.mm_h);
}

@end

@interface FGHelpTemplateView()<UITableViewDataSource, UITableViewDelegate, FGHelpTemplateCategoryViewDelegate>
@property (nonatomic, strong) FGHelpTemplateCategoryView *categoryView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *exchangeButton;
@property (nonatomic, assign) NSInteger selectedIndex;
@property (nonatomic, strong) id templateData;
@property (nonatomic, strong) NSArray *totalDataArray;
@property (nonatomic, assign) NSInteger currentPage; // 当前页
@property (nonatomic, strong) NSArray *currentPageDataArray; // 当前页数据
@property (nonatomic, assign) NSInteger startIndex;
@property (nonatomic, strong) NSArray *dataArray; // tableView显示数据
@end

@implementation FGHelpTemplateView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        // categoryView
        _categoryView = [FGHelpTemplateCategoryView new];
        _categoryView.delegate = self;
        [_categoryView fillData:@[@"帮助中心", @"账号相关", @"产品相关", @"产品相关"]];
        [self addSubview:_categoryView];
        
        // tableView
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.scrollEnabled = NO;
        _tableView.rowHeight = 50;
        _tableView.separatorColor = [UIColor fg_colorWithString:@"#EBF1F5"];
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [self addSubview:_tableView];
        
        // exchangeButton
        _exchangeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_exchangeButton setTitle:@"换一批" forState:0];
        [_exchangeButton setTitleColor:[UIColor fg_colorWithString:@"#558DFF"] forState:0];
        _exchangeButton.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
        _exchangeButton.backgroundColor = [UIColor fg_colorWithString:@"#EBF2FF"];
        _exchangeButton.layer.cornerRadius = 17;
        [_exchangeButton addTarget:self action:@selector(exchangeAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_exchangeButton];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    _categoryView.frame = CGRectMake(0, 0, self.mm_w, 42);
    
    _tableView.frame = CGRectMake(0, 42, self.mm_w, self.mm_h - 52 - (_exchangeButton.hidden ? 0 : 54));
    
    _exchangeButton.mm_left(10).mm_bottom(10).mm_width(104).mm_height(34);
}

#pragma mark - Private Mehtod

- (void)setupCurrentPage:(NSInteger)page
{
    self.startIndex = 0;
    self.currentPage = page;
    if (self.totalDataArray.count == 0) {
        self.dataArray = nil;
        [self.tableView reloadData];
        return;
    }
    self.currentPageDataArray = self.totalDataArray[self.currentPage][@"data"];
    [self setupDataArray];
}

- (void)setupDataArray
{
    self.exchangeButton.hidden = self.currentPageDataArray.count <= 5;
    
    NSMutableArray *arr = [NSMutableArray new];
    [self.currentPageDataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (self.startIndex <= idx && idx < self.startIndex + 5) {
            [arr addObject:obj];
        }
    }];
    self.dataArray = arr;
    
    if (self.startIndex + 5 >= self.currentPageDataArray.count) {
        self.startIndex = 0;
    } else {
        self.startIndex += 5;
    }
    
    [self.tableView reloadData];
}

#pragma mark - Response Event

- (void)exchangeAction:(UIButton *)sender
{
    [self setupDataArray];
}

#pragma mark - FGHelpTemplateCategoryViewDelegate

- (void)helpTemplateCategoryViewDidSelectedIndex:(NSInteger)selectedIndex
{
    [self setupCurrentPage:selectedIndex];
}

#pragma mark - UITableViewDataSource & UITableViewDelegate

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    NSDictionary *data = self.dataArray[indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FGInterestTemplateViewCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FGInterestTemplateViewCell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
    }
    
    cell.textLabel.text = data[@"title"];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(self.isPreview) {
        return;
    }
    
    NSDictionary *data = self.dataArray[indexPath.row];
    if ([self.baseDelegate respondsToSelector:@selector(templateView:didSelectedCell:)]) {
        [self.baseDelegate templateView:self didSelectedCell:data];
    }
}

#pragma mark - Rewrite Mehtod

- (void)fillData:(id)templateData {
    self.templateData = templateData;
    self.totalDataArray = [self.templateData valueForKeyPath:@"data"];
    
    [self.categoryView fillData:[self.totalDataArray valueForKeyPath:@"title"]];
    
    [self setupCurrentPage:0];
}

/*
 {
     "isView":true,
     "id":2,
     "data":[
         {
             "id":128,
             "title":"账号相关1",
             "companyId":1,
             "sort":0,
             "data":[
                 {
                     "operationType":1,
                     "content":"",
                     "id":113,
                     "isRecommend":true,
                     "title":"账号无法登录",
                     "updateTime":"2022-10-26 09:22:22",
                     "tagId":128,
                     "createTime":"2022-10-26 09:22:22",
                     "url":"https:\/\/www.cnblogs.com\/zhaoxiaobei\/p\/9283875.html"
                 }
             ],
             "websiteId":1
         },
         {
             "id":129,
             "title":"产品问题2",
             "companyId":1,
             "sort":1,
             "data":[
                 {
                     "operationType":1,
                     "content":"",
                     "id":114,
                     "isRecommend":false,
                     "title":"产品价格",
                     "updateTime":"2022-10-26 09:24:01",
                     "tagId":129,
                     "createTime":"2022-10-26 09:24:01",
                     "url":"http:\/\/jsrun.net\/vWVKp\/edit"
                 }
             ],
             "websiteId":1
         }
     ],
     "children":null,
     "type":2,
     "tips":"帮助模板",
     "name":"帮助模板",
     "pid":0
 }
 */

@end
